package com.sooth.system.user.service;

import cn.hutool.core.collection.CollUtil;
import com.dream.template.mapper.TemplateMapper;
import com.sooth.system.user.mapper.SysUserRoleMapper;
import com.sooth.system.user.table.SysUserRole;
import com.sooth.system.user.view.SysUserRoleDto;
import com.sooth.system.user.view.SysUserRoleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserRoleServiceImpl implements ISysUserRoleService {
    private final TemplateMapper templateMapper;

    private final SysUserRoleMapper userRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserRoleVo userRoleVo) {
        Long userId = userRoleVo.getUserId();
        userRoleMapper.deleteByUserId(userId);
        List<Long> roleIds = userRoleVo.getRoleIds();
        if (CollUtil.isNotEmpty(roleIds)) {
            List<SysUserRole> userRoles = new ArrayList<>(roleIds.size());
            for (Long roleId : roleIds) {
                userRoles.add(new SysUserRole(userId, roleId));
            }
            templateMapper.batchInsert(userRoles);
        }
    }

    @Override
    public List<SysUserRole> selectList(SysUserRoleDto userRoleDto) {
        return templateMapper.selectList(SysUserRole.class, userRoleDto);
    }
}
